#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
from contextlib import closing
import os

from base_pipeline import ItemPipeline
from downloader import ProgressBar


class FileDownloadPipeline(ItemPipeline):
    def __init__(self, path="download"):
        super(FileDownloadPipeline, self).__init__()
        self.__path = path
        is_exist = os.path.exists(path)
        if not is_exist:
            os.mkdir(path)


    def process_item(self, item):
        if not item:
            pass
        url = item["src"]
        filename = url.split('/')[-1]
        with closing(requests.get(url, stream=True)) as response:
            chunk_size = 1024
            content_size = int(response.headers['content-length'])
            if response.status_code == 200:
                print('文件大小:%0.2f' % (content_size / chunk_size))
                progress = ProgressBar(
                    "%s下载进度" % filename,
                    total=content_size,
                    unit="KB",
                    chunk_size=chunk_size,
                    run_status="正在下载",
                    fin_status="下载完成")
                filepath = "./%s/%s" % (self.__path, filename)
                with open(filepath, "wb") as file:
                    for data in response.iter_content(chunk_size=chunk_size):
                        file.write(data)
                        progress.refresh(count=len(data))
            else:
                print('链接异常')
